package General;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.util.Formatter;
/**
 * Create check sum for a file
 * @author Guy & Liel
 *
 */
public class Hash {

	/**
	 * return a check sum
	 * @param fileName
	 * @return String
	 * @throws Exception
	 */
	public static String getHashFile(String fileName) throws Exception
	{
		MessageDigest sha1 = MessageDigest.getInstance("SHA1");
		System.out.println("I am in Hash");
		return Hash.calculateHash(sha1, fileName);
	}
	/**
	 * Calculate an check sum according to algorithm and file
	 * @param algorithm
	 * @param fileName
	 * @return String
	 * @throws Exception
	 */
    public static String calculateHash(MessageDigest algorithm, String fileName) throws Exception
    {
    	new File (fileName);
    	System.out.println("The file name is "+ fileName);
        FileInputStream fis = new FileInputStream(fileName);
        BufferedInputStream bis = new BufferedInputStream(fis);
        DigestInputStream dis = new DigestInputStream(bis, algorithm);

        while (dis.read() != -1);
        byte[] hash  = algorithm.digest();
        return byteArray2Hex(hash);
    }

    private static String byteArray2Hex(byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        return formatter.toString();
    }

}